package demo.db.maxmind;

import com.alibaba.fastjson.JSON;
import com.maxmind.db.CHMCache;
import com.maxmind.db.Reader;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;


/**
 * MaxMind GeoIP2 是 MaxMind 公司推出的 IP 地址定位库，可根据 IP 地址查找地理位置信息，应用广泛。
 * <p>
 * 以下是详细介绍：
 *
 * <li>GeoIP2 商业版：提供精准的 IP 地址定位服务，能获取详细的地理位置信息。
 * <li>GeoLite2 免费版：是 GeoIP2 的免费版本，准确率稍低于付费版。包含 GeoLite2 国家库、GeoLite2 城市库和 Geolite2 ASN 等部分。
 * 国家库可查询 IP 地址所在国家和洲；
 * 城市库能查询国家、地区、城市、经纬度和邮政编码等；
 * Geolite2 ASN 用于查询 IP 地址所属的自治域 AS 或运营商 ISP。
 *
 * <p>
 * <a href="https://www.maxmind.com/en/accounts/1197913/geoip/downloads">GeoLite City下载地址</>
 */
public class MaxMindDemo {

    @Test
    public void demo1() throws FileNotFoundException {
        File file = new File("/Users/stan/Downloads/GeoLite2-City-20250701.mmdb");
        try (InputStream inputStream = new FileInputStream(file)) {
            DatabaseReader dbReader = new DatabaseReader.Builder(inputStream)
                    .fileMode(Reader.FileMode.MEMORY)
                    .withCache(new CHMCache())
                    .build();
            System.out.println("加载本地GeoLite2文件成功");

            InetAddress ipAddress = InetAddress.getByName("183.195.45.252");
            CityResponse response = dbReader.city(ipAddress);
            System.out.println(JSON.toJSONString(response, true));

            System.out.println("City: " + JSON.toJSONString(response.getCity(), true));

            CommonRep rep = CommonRep.from(response);
            System.out.println(JSON.toJSONString(rep, true));
        } catch (IOException e) {
            System.err.println("加载本地GeoLite2文件异常:" + e);
        } catch (GeoIp2Exception e) {
            throw new RuntimeException(e);
        }

//        try (InputStream inputStream = new ClassPathResource("GeoLite2-City-20250701.mmdb").getInputStream()) {
//
//
//        } catch (IOException e) {
//            System.err.println("加载本地GeoLite2文件异常:" + e);
//        }
    }

    @Test
    public void testAli() {
        String host = "https://c2ba.api.huachen.cn";
        String path = "/ip";
        String method = "GET";
        String appcode = "162ba253902646e199dcb08418d64aac";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("ip", "218.18.228.178");


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             *
             * <pre>
             *     {
             *   "ret": 200,
             *   "msg": "success",
             *   "data": {
             *     "ip": "218.18.228.178",
             *     "long_ip": "3658671282",
             *     "isp": "中国电信",
             *     "area": "华南",
             *     "region_id": "440000",
             *     "region": "广东",
             *     "city_id": "440300",
             *     "city": "深圳",
             *     "district": "南山区",
             *     "district_id": "440305",
             *     "country_id": "CN",
             *     "country": "中国",
             *     "lat": "22.528499",
             *     "lng": "113.923552"
             *   },
             *   "log_id": "421366015e6645deba0279287b73bf88"
             * }
             * <pre/>
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            //获取response的body

            String aliData = EntityUtils.toString(response.getEntity());

            System.out.println(aliData);

            if (aliData == null) {
                return;
            }
            CommonRep rep = CommonRep.from(aliData);
            System.out.println(JSON.toJSONString(rep, true));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
